<template>
  <div class="personBooking">
    <template v-if="calendarStatus == 1">
      <!-- 散客预约 -->
      <div class="date">
        <date-picker
          @dayStatus="dayStatus"
          :calendarInfo="calendarInfo"
          @checkDay="checkDay"
          @initTpList="initTpList"
          v-if="calendarInfo.yy_date.length > 0"
        ></date-picker>
      </div>
      <div class="timeIn">
        <h3 class="title">入馆时段</h3>
        <div class="times">
          <div
            :class="{ time: true, check: tp_id == time.tp_id }"
            v-for="time in tpList"
            :key="time.tp_id"
            @click="checkTime(time)"
          >
            <p class="name">{{ time.time_show }}</p>
            <!-- <p class="surplus">余票：{{remainTicket(time.tickets)}}</p> -->
            <!-- v-show="remainTicket(time.tickets)" -->
          </div>
        </div>
        <div class="picks">
          <div class="pick" v-for="(ticket, index) in tickets" :key="index">
            <div class="name">
              <span class="label">{{ ticket.ticket_name }}：</span>

              <span class="money">¥ {{ ticket.ticket_price }}/人</span>
            </div>
            <div>
              <!-- <my-step v-model="nums[ticket.td_tp_id]" :setvalue="0" :min="0"></my-step> -->
              <van-stepper
                class="step"
                min="0"
                v-model="nums[ticket.td_tp_id]"
                theme="round"
                button-size="22"
              />
            </div>
          </div>
        </div>
        <p class="note">(注：优惠票的涉及群体，例如：老年，学生)</p>
        <!-- <div class="children"> -->
        <!-- <div class="pick"> -->
        <!-- <div class="name"> -->
        <!-- <span class="label">随行儿童：</span> -->
        <!-- </div> -->
        <!-- <div> -->
        <!-- <van-stepper class="step" min="0" v-model="childNums" theme="round" button-size="22" -->
        <!-- disable-input/> -->
        <!-- </div> -->
        <!-- </div> -->
        <!-- </div> -->
      </div>
      <van-cell-group>
        <van-field
          label="姓   名"
          placeholder="请输入姓名"
          v-model="user_name"
          required
        />
        <van-field
          label="手机号码"
          placeholder="请输入手机号码"
          v-model="user_phone"
          type="tel"
          required
        />
        <van-field
          required
          readonly
          clickable
          name="picker"
          label="证件类型"
          placeholder="点击选择证件类型"
          @click="showPicker = true"
          :value="card_type_active.card_type"
          right-icon="arrow"
        />
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="card_type"
            @confirm="onConfirmCard"
            @cancel="showPicker = false"
            value-key="card_type"
          />
        </van-popup>
        <van-field
          label="证件号"
          placeholder="请输入证件号"
          :border="false"
          v-model="id_card"
          required
        />
      </van-cell-group>

      <div class="showCoupon">
        <div class="radioBox">
          <!-- <span :class="['radio',checkCouple&&checkCouple.id?'check':'']">
                    <van-icon name="success"/>
                </span> -->
          <span
            :class="{ title: true, check: checkCouple && checkCouple.id }"
            >{{ couponTip }}</span
          >
        </div>
        <span
          :class="{ more: true, check: checkCouple && checkCouple.id }"
          @click="openCoupons"
        ></span>
      </div>
    </template>

    <!-- 闭馆 -->
    <template v-if="calendarStatus == 9002">
      <div class="closes_box">
        <img src="../../../../static/img/closes.png" alt="" />
        <p>{{ calendarMsg }}</p>
      </div>
    </template>

    <div class="notice">
      <p class="title">参观须知</p>
      <div
        class="artical"
        style="white-space: pre-wrap;"
        v-html="textTip"
      ></div>
    </div>
    <div class="total">
      <p>
        合计金额：
        <span class="money">¥{{ total }}</span>
        <span class="num">（{{ totalNum }}张）</span>
      </p>
      <div class="btn" v-if="calendarStatus == 1" @click="ticketorder">
        提 交
      </div>
      <div class="btn hui" v-else>提 交</div>
    </div>
    <van-overlay
      :show="show"
      :duration="0.5"
      :lock-scroll="false"
      @click="show = false"
    >
      <div v-show="show" :class="['couponBox', 'in']" @click.stop>
        <div class="header">
          <span class="header_name">更多优惠券</span>
          <span class="explain">使用说明</span>
        </div>
        <ul class="coupons">
          <li
            class="coupon"
            @click="checkCoupon(i)"
            v-for="(i, index) in myCoupon"
            :key="index"
          >
            <div class="left">
              <p class="money">
                ¥
                <span>{{ parseFloat(i.cprice) }}</span>
              </p>
              <p class="tip">{{ i.range_name }}</p>
            </div>
            <div class="right">
              <p class="name">{{ i.coupon_name }}</p>
              <p class="time">有效期至：{{ i.date }}</p>
              <p class="remain">还剩 9 天过期</p>
            </div>
            <div class="radioBox">
              <div :class="['radio', checkCouple.id == i.id ? 'check' : '']">
                <van-icon name="success" />
              </div>
            </div>
          </li>
        </ul>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import datePicker from "../../../components/personDatePicker";
import myStep from "../../../components/step";
import {
  getDate,
  CouponMyCoupon,
  pertextTip,
  ticketorder,
  getCardTypeLists,
} from "../../../http/interface";
import { Session, checkIdcardValid } from "../../../assets/js/utils";
import { checkPhone } from "../../../assets/js/assist";

export default {
  name: "",
  components: {
    datePicker,
    myStep,
  },
  data() {
    return {
      calendarStatus: -1,
      calendarMsg: "",
      calendarInfo: {
        yy_date: [],
      },
      dayInfo: {},
      tpList: [], //person_tp_list
      tickets: [],
      showPicker: false,
      card_type: [
        {
          card_type: "身份证",
          cardtype_id: 1,
        },
      ],
      card_type_active: {},
      tp_id: "",
      show: false,
      nums: {},
      myCoupon: [],
      checkCouple: {}, //支付核销优惠劵
      textTip: "",
      preson_td_id: "",
      isDayCheck: false,
      childNums: 0,
      user_phone: "",
      user_name: "",
      id_card: "",
    };
  },
  computed: {
    total() {
      let num = 0;
      let keys = Object.keys(this.nums);
      keys.forEach((e) => {
        let price = this.tickets.filter((t) => {
          return t.td_tp_id == e;
        })[0].ticket_price;
        num += ((price * 100) / 100) * this.nums[e];
      });
      num -= parseFloat(this.checkCouple.cprice) || 0;
      //总价小于0返回0
      if (num <= 0) {
        return 0;
      }
      return num.toFixed(2);
    },
    totalNum() {
      let num = 0;
      let keys = Object.keys(this.nums);
      for (let i in this.nums) {
        num += this.nums[i];
      }
      return num;
    },
    couponTip() {
      // myCoupon.length>0?'使用优惠券抵扣'+parseFloat(checkCouple.cprice)+'元':'暂无可用优惠券'

      if (this.myCoupon.length >= 1) {
        if (this.checkCouple && this.checkCouple.id) {
          return "使用优惠券抵扣" + parseFloat(this.checkCouple.cprice) + "元";
        } else {
          return "请选择可使用的优惠卷";
        }
      } else {
        return "暂无可用优惠券";
      }
    },
  },
  mounted() {
    let api_token = this.$route.query.api_token;
    if (api_token) {
      localStorage.setItem("api_token", this.$route.query.api_token || "");
    }
    this.initSession();
    this.getDate();
    this.getMyCoupon();
    this.getPertextTip();
  },
  methods: {
    dayStatus(value) {
      this.isDayCheck = value;
    },
    initSession() {
      //初始化天
      // this.preson_td_id = Session.get('preson_td_id')
      // 初始化时间段
      this.tpList = Session.get("person_tp_list") || [];
      // 初始化选中时间段
      this.tp_id = Session.get("person_tp_id") || "";
      //初始化step
      // this.tickets = Session.get('person_tickets_list')||[]
    },
    async getMyCoupon() {
      try {
        const res = await CouponMyCoupon(2, 0);
        if (res.status == 1) {
          this.myCoupon = res.data;
          if (this.myCoupon.length >= 1) {
            this.checkCouple = this.myCoupon[0];
          }
        } else {
        }
      } catch (error) {}
    },
    async getDate() {
      try {
        const card_type_lists = await getCardTypeLists();
        const res = await getDate();
        this.calendarStatus = res.status;
        this.calendarMsg = res.msg;
        if (res.status == 1) {
          this.calendarInfo = res.data;
        } else if (res.status == 9001) {
          this.$router.replace("/ticket");
        } else {
        }
        if (card_type_lists.status == 1 && card_type_lists.data.length) {
          this.card_type = card_type_lists.data;
          this.card_type_active = card_type_lists.data[0];
        }
      } catch (error) {}
    },
    checkDay(day) {
      if (day.td_id) {
        Session.set("preson_td_id", day.td_id);
      } else {
        Session.set("preson_td_id", null);
      }
      this.tpList = day.timeInfoList;
      Session.set("person_tp_list", this.tpList || []);
      Session.set("person_tp_id", null);
      this.initTickets(this.tpList && this.tpList[0].tickets);
      this.clearTime();
    },
    initTpList(list) {
      let savelist = Session.get("person_tp_list");
      if (savelist && savelist.length) {
        this.tpList = savelist;
        this.initTickets(Session.get("person_tickets_list"));
      } else {
        this.tpList = list;
        this.initTickets(this.tpList[0].tickets);
      }
    },
    initTickets(value) {
      this.tickets = value;
      this.initNums();
    },
    checkTime(time) {
      let num = 0;
      time.tickets.forEach((e) => {
        num += e.tp_last_stock;
      });
      if (num <= 0) {
        this.$toast("该时段无票");
        return;
      }
      if (this.tp_id == time.tp_id) {
        this.clearTime();
        Session.set("person_tp_id", null);
      } else {
        this.tp_id = time.tp_id;
        Session.set("person_tp_id", this.tp_id);
      }
      Session.set("person_tickets_list", time.tickets);
      this.initTickets(time.tickets);
    },
    clearTime() {
      this.tp_id = "";
    },
    remainTicket(arr) {
      let ticketNum = 0;
      arr.forEach((e) => {
        ticketNum += e.tp_last_stock;
      });
      return ticketNum;
    },
    initNums() {
      this.nums = {};
      for (let i in this.tickets) {
        this.$set(this.nums, this.tickets[i].td_tp_id, 0);
      }
    },
    openCoupons() {
      if (this.myCoupon.length == 0) {
        return;
      }
      this.show = true;
    },
    checkCoupon(value) {
      if (this.checkCouple.id == value.id) {
        this.checkCouple = {};
      } else {
        this.checkCouple = value;
      }
    },
    onConfirmCard(value, index) {
      this.card_type_active = value;
      console.log(value);
      this.showPicker = false;
    },
    async getPertextTip() {
      try {
        const res = await pertextTip();
        if (res.status == 1) {
          this.textTip = res.data.text_tip;
        } else {
        }
      } catch (error) {}
    },
    async ticketorder() {
      // return this.$toast('暂未开放预约')  // 7.28 //7.30
      try {
        if (!this.isDayCheck) {
          this.$toast("请选择参观日期");
          return;
        }
        if (!this.tp_id) {
          this.$toast("请选择参观时间");
          return;
        }
        if (this.user_name == "") {
          return this.$toast("请输入姓名");
        }
        if (!checkPhone(this.user_phone)) {
          return this.$toast("请输入正确的手机号");
        }
        let chekIdCardInfo = checkIdcardValid(
          this.card_type_active.cardtype_id,
          this.id_card
        );
        if (!chekIdCardInfo.status) {
          return this.$toast(chekIdCardInfo.errtips);
        }
        // console.log(chekIdCardInfo)
        let td_tp_id = [];
        let td_tp_id_count = [];
        let pt_id = [];
        let id;
        for (let i in this.nums) {
          if (this.nums[i] > 0) {
            td_tp_id.push(i);
            td_tp_id_count.push(this.nums[i]);
            let tickit_pt_id = this.tickets.filter((t) => {
              return t.td_tp_id == i;
            })[0].pt_id;
            pt_id.push(tickit_pt_id);
          }
          // td_tp_id.push(i)
          // td_tp_id_count.push(this.nums[i])
          // let tickit_pt_id = this.tickets.filter(t => {
          //     return t.td_tp_id == i
          // })[0].pt_id
          // pt_id.push(tickit_pt_id)
        }
        let data = {
          td_tp_id: td_tp_id,
          td_tp_id_count: td_tp_id_count,
          pt_id: pt_id,
          user_name: this.user_name,
          user_phone: this.user_phone,
          id_card: this.id_card,
          cardtype_id: this.card_type_active.cardtype_id,
        };
        /**
         * 3.1移除随行儿童
         */
        // let a = td_tp_id_count[0] || 0//标准票数量
        // let b = td_tp_id_count[1] || 0//优惠票数量
        // if (this.childNums <= (a + b) * 2) {//随行儿童个数，最多等于（标准票+优惠票）*2
        //     data.child_count = this.childNums
        // } else {
        //     this.$toast('一个成人最多可带2名1.2米以下的未成年人')
        //     return
        // }

        if (this.checkCouple && this.checkCouple.id) {
          id = this.checkCouple.id;
          data.id = id;
        }
        if (td_tp_id.length <= 0) {
          this.$toast("请选择购买门票");
          return;
        }
        // console.log(data)
        const res = await ticketorder(data);
        if (res.status == 1) {
          this.$router.push({
            path: "/personOrder",
            query: {
              orderId: res.data.torder_id,
              score: res.data.score,
            },
          });
        } else {
          this.$toast(res.msg);
        }
      } catch (error) {}
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../style/mixin.scss";

.personBooking {
  padding-bottom: 170px;
  background: #eeeeee;

  .closes_box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #ffffff;
    padding: 36px 100px;
    border-radius: 24px;
    margin-bottom: 20px;

    img {
      width: 400px;
      height: auto;
    }
    p {
      text-align: center;
      font-size: 28px;
      line-height: 1.6;
    }
  }

  .date {
    max-width: 10rem;
    margin: 0 auto;
  }

  .timeIn {
    width: 100%;
    min-height: 410px;
    border-radius: 24px;
    background: #ffffff;
    margin-top: 20px;
    padding: 36px 30px;

    .title {
      font-size: 30px;
      font-weight: bold;
      color: #353535;
    }

    .times {
      margin-top: 29px;
      display: flex;
      justify-content: space-between;
      // overflow-x: auto;

      .time {
        // width: 200px;
        flex: 1;
        height: 84px;
        background: #feeece;
        border-radius: 10px;
        padding: 12px 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex-shrink: 0;
        // margin-right: 60px;
        margin: 0 12px;

        &.check {
          background: #f8a80b;
          position: relative;

          &::after {
            content: "";
            width: 52px;
            height: 52px;
            position: absolute;
            right: 0;
            bottom: 0;
            background: url("../../../../static/img/checktime.png") no-repeat
              center center;
            background-size: 52px 52px;
          }

          .name {
            color: #ffffff;
          }

          .surplus {
            color: #ffffff;
          }
        }

        .name {
          font-size: 30px;
          font-weight: 500;
          text-align: center;
          color: #646464;
          line-height: 60px;
        }

        .surplus {
          font-size: 24px;
          font-weight: 400;
          text-align: center;
          color: #646464;
        }
      }
    }

    .picks {
      margin-top: 40px;

      .pick {
        width: 100%;
        // height: 48px;
        display: flex;
        justify-content: space-between;
        margin-bottom: 28px;

        .name {
          font-size: 30px;
          font-weight: 500;
          color: rgba(50, 50, 50, 1);
          line-height: 48px;
          max-width: 60%;

          .label {
            // white-space: nowrap;
            display: inline-block;
          }

          .money {
            color: #e10028;
          }
        }

        /deep/ .step {
          button {
            background-color: #ffffff;
            color: #f17f2a;
            border: 1px solid #e5e5e5;
          }

          .stepper__minus {
            &::before {
              width: 2px;
            }
          }

          .van-stepper__plus {
            &::after {
              width: 2px;
            }
          }

          .van-stepper__minus--disabled {
            color: #b1b2b4;
          }
        }
      }
    }

    .note {
      font-size: 24px;
      font-weight: 400;
      color: rgba(100, 100, 100, 1);
      margin-top: 20px;
      line-height: 1.5;
    }

    .children {
      margin-top: 20px;

      .pick {
        width: 100%;
        // height: 48px;
        display: flex;
        justify-content: space-between;
        margin-bottom: 28px;

        .name {
          font-size: 30px;
          font-weight: 500;
          color: rgba(50, 50, 50, 1);
          line-height: 48px;
          max-width: 60%;

          .label {
            // white-space: nowrap;
            display: inline-block;
          }

          .money {
            color: #e10028;
          }
        }

        /deep/ .step {
          button {
            background-color: #ffffff;
            color: #f17f2a;
            border: 1px solid #e5e5e5;
          }

          .stepper__minus {
            &::before {
              width: 2px;
            }
          }

          .van-stepper__plus {
            &::after {
              width: 2px;
            }
          }

          .van-stepper__minus--disabled {
            color: #b1b2b4;
          }
        }
      }
    }
  }
  /deep/ .van-cell-group {
    border-radius: 24px;
    margin-top: 20px;
    overflow: hidden;
    padding: 0 40px;
  }
  .showCoupon {
    height: 104px;
    padding: 0 40px;
    border-top: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #ffffff;
    border-radius: 24px;
    margin-top: 20px;

    .radioBox {
      height: 100%;
      display: flex;
      align-items: center;

      .radio {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        font-size: 18px;
        background: #dfdfdf;
        color: #ffffff;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 29px;

        &.check {
          background: #f17f2a;
          animation: smallToBig 0.2s;
        }
      }

      .title {
        font-size: 30px;
        font-weight: 500;
        color: rgba(50, 50, 50, 1);
        line-height: 85px;
        &.check {
          color: #f17f2a;
        }
      }
    }

    .radioSpan {
      font-size: 30px;
      line-height: 104px;
      max-width: 560px;
      display: inline-block;
      @include ellipsis(1);
    }

    .more {
      width: 36px;
      height: 36px;
      display: inline-block;
      background: url("../../../../static/img/zanwugengduo.png") no-repeat
        center center;
      background-size: 100% 100%;
      &.check {
        background: url("../../../../static/img/zanwugengduo1.png") no-repeat
          center center;
        background-size: 100% 100%;
      }
    }
  }

  .notice {
    width: 100%;
    min-height: 355px;
    padding: 36px 30px;

    .title {
      font-size: 30px;
      font-weight: bold;
      color: rgba(50, 50, 50, 1);
      margin-bottom: 30px;
    }

    .artical {
      font-size: 28px;
      font-weight: 400;
      color: rgba(50, 50, 50, 1);
      line-height: 48px;
    }
  }

  .total {
    width: 100%;
    height: 170px;
    background: #ffffff;
    position: fixed;
    bottom: 0;
    border-top-left-radius: 24px;
    border-top-right-radius: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;

    p {
      font-size: 32px;
      font-weight: 500;
      color: rgba(50, 50, 50, 1);
      max-width: 420px;
      word-break: break-all;

      .money {
        color: #e10028;
      }

      .num {
        color: #646464;
      }
    }

    .btn {
      width: 240px;
      height: 72px;
      border-radius: 36px;
      background: #f17f2a;
      color: #ffffff;
      line-height: 72px;
      text-align: center;
      font-size: 32px;

      &:active {
        background: #ed9f65;
      }
      &.hui {
        background-color: #cccccc;
        &:active {
          background: #cccccc;
        }
      }
    }
  }

  .couponBox {
    width: 100%;
    max-height: 664px;
    background: #ffffff;
    position: absolute;
    bottom: 0;

    &.in {
      animation: fadeInUpBig;
      animation-duration: 0.7s;
    }

    .header {
      width: 100%;
      height: 116px;
      padding: 0 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header_name {
        font-size: 32px;
        font-weight: 500;
        color: rgba(50, 50, 50, 1);
        line-height: 32px;
        border-left: 3px solid #f28000;
        text-indent: 21px;
      }

      .explain {
        font-size: 28px;
        font-weight: 400;
        color: rgba(50, 50, 50, 1);
        line-height: 116px;
      }
    }

    .coupons {
      max-height: 664px - 116px;
      padding: 0 30px;
      overflow-y: auto;

      .coupon {
        width: 100%;
        height: 202px;
        background: url("../../../../static/img/youhuiquan.png") no-repeat left
          center;
        background-size: 254px 202px;
        margin-bottom: 30px;
        border: 2px dashed #fc6f59;
        border-left: none;
        display: flex;

        .left {
          width: 254px;
          height: 100%;
          padding: 33px 0;
          text-align: center;
          // background: yellowgreen;
          .money {
            font-size: 28px;
            color: #ffffff;
            line-height: 100px;

            span {
              font-size: 64px;
            }
          }

          .tip {
            font-size: 24px;
            font-weight: 500;
            color: rgba(255, 255, 255, 1);
          }
        }

        .right {
          flex: 1;
          padding: 32px 30px;

          .name {
            font-size: 32px;
            font-weight: 500;
            color: rgba(50, 50, 50, 1);
            @include ellipsis(2);
          }

          .time {
            font-size: 26px;
            font-weight: 500;
            color: rgba(50, 50, 50, 1);
            // line-height: 82px;
            margin: 10px 0;
          }

          .remain {
            font-size: 24px;
            font-weight: 400;
            color: rgba(100, 100, 100, 1);
          }
        }

        .radioBox {
          width: 80px;
          display: flex;
          justify-content: center;
          align-items: center;

          .radio {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            font-size: 18px;
            background: #dfdfdf;
            color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;

            &.check {
              background: #f17f2a;
              animation: smallToBig 0.2s;
            }
          }

          @keyframes smallToBig {
            0% {
              transform: scale(0);
            }
          }
        }
      }
    }
  }
}
</style>
